/**
  imgServer.java is part of Marioneta.

  Marioneta is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License.

  Marioneta is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
  
  @author martin
   Martin Edmundo Barriga Orozco, 2008
   martin.barriga@gulmore.org
 
 imgServer: La funcion de este servidor es unicamente recibir las imagenes
 que llegan del cliente y ponerlas a disposicion de otras clases.
 */

package escritorioremoto;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

import java.net.Socket;
import java.net.ServerSocket;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class imgServer extends netUtils implements Runnable {
    private ServerSocket imgServer;
    
    //Contructor usado en contexto de globalServer
    public imgServer( Socket sk, int id ){
        this.initVal( sk, id );
    }
    
    //Contructor usado en contexto sin globalServer
    public imgServer( Socket sk ){
        this.initVal( sk, 0 );
    }
    
    public imgServer(int port){
        try{
            imgServer = new ServerSocket( port );
        }
        catch(IOException e){
            System.out.print( "ctor"+ e.getMessage() );
        }
    }
    
    @Override
    public void initProc(){
    }
    
    public Image getting_img(){
        Image imgBackground = null;
        BufferedImage bufferedImage;
        try{
            System.out.print("Esperado buffer... ");
            do{
                bufferedImage = ImageIO.read( this.getInputStreamSocket() );
            }while( bufferedImage == null );
            System.out.print("  [ OK ]\n");
            
            //Despues de leer la imagen, se prepara para presentarle en el GUI
            ByteArrayOutputStream osImg = new ByteArrayOutputStream();
            if (ImageIO.write( bufferedImage, "png", osImg ) == true){
                byte[] bytesImagen = osImg.toByteArray();
            
                //Objeto de Imagen listo
                imgBackground = Toolkit.getDefaultToolkit().createImage( bytesImagen );
            
                //Si deseamos mandar a un archivo
                ImageIO.write(bufferedImage, "png", new File("desktop2") );
            }
        }
        catch(IOException e){
            System.out.println("Error al recibir la imagen: "+ e.getMessage() );
        }
        return imgBackground;
    }

    @Override
    public void run(){
        boolean vive = true;
        int ctes = 0;
        //REVISAR
        while (vive){
            try{
                System.out.println("Esperando cliente [ " + ctes +" ]... ");
                Socket Sock = imgServer.accept();

                System.out.print( "valor del socket asignado: " + Sock.toString() );
                
                //Se inicializa los valores para ese cliente
                initVal( Sock, ctes++ );
            }
            catch(IOException exIO){
                System.out.println("Error al esperar conexiones: "+ exIO.getMessage() );
                System.out.println("Saliendo...");
                vive = false;
            }
            catch(Exception e){
                System.out.println("Error generic: " );
                e.printStackTrace();
                System.out.println("Saliendo...");
                vive = false;
            }
        }
    }
    
}
